fn unhidePickBox = 
(
	for geo in geometry do
	(
		if getUserProp geo "vision_physics_userData" != undefined then
		(
			geo.isHidden = false
		)
    )
)

fn rotateRoot degree = 
(
	for o in objects do
	(
		if o.name == "centerdown#1" then o.rotation.z_rotation = degree
	)
)

fn isExportType geo = 
(
	local hasRB = geo.modifiers[hkRigidBodyModifier] != undefined
	local hasLF = geo.modifiers[hkLocalFrameModifier] != undefined
	local hasCC = geo.modifiers[hkClothCollidableModifier] != undefined
	return not hasRB and not hasLF and not hasCC and not geo.isHidden and
			findstring geo.name "_" != undefined and
			(iskindof geo editable_mesh or iskindof geo editable_poly or iskindof geo polymeshobject)
)

fn getExportOption exportAnim texPath =
(
	local strAnim = "0"
	if exportAnim then strAnim = "1"
	local strTexture = ""
	if texPath == "" then strTexture = " extractAndCopyTextures 0"
	else strTexture = "extractAndCopyTextures 1 textureSubdir \"" + texPath + "\\\""

	local option = "
	harvestingOptions {
		grabBones 1 
		grabLights 0
		grabMaterials 1 
		grabNormals 1
		grabTangents 1
		grabColors 1
		gragUVs 1 
		uvChannel_diffuse \"1\"
		uvChannel_lightmap \"\"
	}
	optimizations {removeUnskinnedLeafBones 0}
	miscellaneous {exportAnimAlongWithModel " + strAnim + "} 
	postExportOptions {displayViewer 0 " + strTexture + "}"
	return option
)

fn exportNPCModel filename = 
(
	rotateRoot 90
	unhidePickBox()
	local option = getExportOption false "textures"
	exportVisionFileEx filename type:"Model" options:option noprompt:true exportSelected:false
	
	rotateRoot 0
)

fn exportSharedNPC pathgen = 
(
	rotateRoot 90

	pickBox = #()
	for geo in geometry do
	(
		if getUserProp geo "vision_physics_userData" != undefined then
		(
			appendIfUnique pickBox geo
			unhide geo
		)
    )

	for geo in geometry do 
	(
		if isExportType geo then 
		(
			select geo			
			for i = 1 to pickBox.count do 
				selectMore pickBox[i]
			
			local filename = pathgen(geo.name)
			local option = getExportOption false "textures"
			exportVisionFileEx filename type:"Model" options:option noprompt:true exportSelected:true
			clearSelection()
		)
	)
	clearSelection()
	rotateRoot 0
)



fn exportParts pathgen = 
(
	rotateRoot 90
	for geo in geometry do 
	(
		if isExportType geo then 
		(
			select geo
			local filename = pathgen(geo.name)
			local option = getExportOption false "textures"
			exportVisionFileEx filename type:"Model" options:option noprompt:true exportSelected:true
		)
	)
	clearSelection()
	rotateRoot 0
)

------------------------------------------------------------
fn exportClothPartHkt pathgen = 
(
	local exportSel = hkSceneExportUtility.exportSelectedOnly
	local saveEnv = hkSceneExportUtility.environmentVariables
	
	hkSceneExportUtility.exportSelectedOnly = false
	rotateRoot 90
	
	local partsFile = ""
	for geo in geometry do
	(
		if isExportType geo then 
		(
			partsFile += pathgen(geo.name)
			partsFile += "|"
			
		)
	)
	
	local sceneName = maxFilePath + maxFileName
	
	hkSceneExportUtility.environmentVariables = "partfile=" + partsFile + ";logfile=" + sceneName + ".cloth.log"
	hkSceneExportUtility.exportScene true
	
	hkSceneExportUtility.environmentVariables = saveEnv
	hkSceneExportUtility.exportSelectedOnly = exportSel
	rotateRoot 0
)

fn exportSceneClothHkt filename = 
(
	local exportSel = hkSceneExportUtility.exportSelectedOnly
	local saveEnv = hkSceneExportUtility.environmentVariables
	
	hkSceneExportUtility.exportSelectedOnly = false

	
	local sceneName = maxFilePath + maxFileName
	
	hkSceneExportUtility.environmentVariables = "partfile=" + filename + ";logfile=" + sceneName + ".cloth.log"
	hkSceneExportUtility.exportScene true
	
	hkSceneExportUtility.environmentVariables = saveEnv
	hkSceneExportUtility.exportSelectedOnly = exportSel
)
------------------------------------------------------------
fn exportPCAnim filepath = 
(
	local maxname = maxFileName
	local ns = filterString maxname "_"
	local p = ns[1] + "_" + ns[2]
	local filename = filepath + "\\characters\\pc\\" + p + "\\" + p + ".anim"
	unhide objects
	exportVisionFileEx filename type:"Animation" preset:"default" noprompt:false
	local hFile = filepath + "\\characters\\pc\\" + p + "\\" + p + ".hka"
	vAnimToHAnim "plugins\\hkagen.exe" "/m" hFile filename
)

fn exportNPCAnim filepath = 
(
	local maxname = maxFileName
	local ns = filterString maxname "_"
	local p = ns[1] + "_" + ns[2]
	local filename = filepath + "\\characters\\npc\\" + p + "\\" + p + ".anim"
	unhide objects
	exportVisionFileEx filename type:"Animation" noprompt:false preset:"default" exportSelected:true
)

fn exportPCSkeleton filepath =
(
	rotateRoot 90
	unhidePickBox()
	local maxname = maxFileName
	local ns = filterString maxname "_"
	local p = ns[1] + "_" + ns[2]
	local filename = filepath + "\\characters\\pc\\" + p + "\\" + p + ".model"
	local option = getExportOption false ""
	exportVisionFileEx filename type:"Model" noprompt:true options:option
	rotateRoot 0
)

fn convertPhyMat =
(
	for geo in geometry do (
		local colmask = getUserProp geo "vision_physics_colMask" 
		local userdata = getUserProp geo "vision_physics_userData" 
		if colmask == undefined and userdata != undefined then setUserProp geo "vision_physics_colMask" userdata
	)
)

fn exportVmesh filename =
(
	convertPhyMat()
	local option = getExportOption false "textures"
	exportVisionFileEx filename type:"Mesh" noprompt:true options:option
)

fn exportSceneModel filename = 
(
	convertPhyMat()
	local option = getExportOption true "textures"
	exportVisionFileEx filename type:"Model" noprompt:false options:option present:"default"
)

fn exportGfxModel filename =
(
	local option = getExportOption false "."
	exportVisionFileEx filename type:"Model" noprompt:true options:option
)

fn exportGfxModelAnim filename =
(
	local option = getExportOption true "."
	exportVisionFileEx filename type:"Model" noprompt:false options:option preset:"default"
)

rollout rollCollMat "碰撞材质"
(
	local materials = #(
		"无",				-- 0
		"泥土",				-- 1
		"石头",				-- 2
		"草地",				-- 3
		"落叶",				-- 4
		"木地板实心",		-- 5
		"木地板空心",		-- 6
		"竹质空心", 			-- 7
		"沙漠",				-- 8
		"雪地",				-- 9
		"冰面",				-- 10
		"水面",				-- 11
		"溪水浅", 			-- 12
		"溪水深", 			-- 13
		"金属地面",			-- 14
		"虚幻特效地面",		-- 15
		"地毯",				-- 16
		"布绸绢帛",			-- 17
		"湿土,偏水声", 		-- 18
		"湿土,偏土声"		-- 19
	)
	
	radiobuttons radioMat labels:materials
	button btnOK "确定"
	button btnCancle "取消"
	on rollCollMat open do
	(
		local matID = getUserProp $ "vision_physics_userData"
		if matID == undefined then radioMat.state = 1
		else radioMat.state = (matID as integer) + 1
	)
	on btnOK pressed do 
	(
		local matID = radioMat.state - 1
		if matID == 0 then (
			setUserProp $ "vision_export_as" "renderMesh"
			
		)
		else (
			setUserProp $ "vision_export_as" "colMesh"
		)
		setUserProp $ "vision_physics_userData" matID
		setUserProp $ "vision_physics_colMask" matID
		DestroyDialog rollCollMat
	)
	on btnCancle pressed do 
	(
		DestroyDialog rollCollMat
	)
)

fn markCollision =
(
	if selection.count == 1 and 
		(selection[1].parent == undefined or 
		 iskindof selection[1].parent Editable_Mesh or
		 iskindof selection[1].parent Editable_Poly) then (
		CreateDialog rollCollMat
	)
	else (
		local index = 0
		for n in objects do (
			if iskindof n GeometryClass and n.parent != undefined and n.isSelected then (
				local boneName = n.parent.name
				setUserProp n "vision_export_as" "colMesh"
				setUserProp n "vision_physics_userData" ("\""+boneName+"\"")
				setUserProp n "vision_physics_colMask" index
			)
			index = index + 1
		)
	)
)

struct schem_node (name, parent_name, obj)
struct schem_diff_result (in_prev_only, in_last_only, in_both)

fn isSameNode n1 n2 = 
(
	return ((n1 == undefined and n2 == undefined) or 
		(n1 != undefined and n2 != undefined and 
			n1.name == n2.name and
			n1.parent_name == n2.parent_name))
)

fn compareSort v1 v2 = 
(
	return stricmp v1.name v2.name
)

fn retrieveSchematic get_obj =
(
	objCollection = #()
	for o in objects do
	(
		if(iskindof o Dummy or 
			iskindof o Biped_Object or 
			iskindof o Editable_Poly) then
		(
			par_name = "undefined"
			tmp_obj = undefined
			if get_obj then
				tmp_obj = o
			
			if o.parent != undefined then
			(
				par_name = o.parent.name
			)
			tmp = schem_node o.name par_name tmp_obj
			appendIfUnique objCollection tmp
		)
	)
	qsort objCollection compareSort
	print "RETRIEVE SCHEMATIC INFORMATION SUCCEEDED"
	return objCollection
)

fn compareSchematic pre cur = 
(
	prev_only = #()
	last_only = #()
	the_same = #()
	for i = 1 to pre.count do
	(
		local find = false
		for j = 1 to cur.count do
		(
			if isSameNode pre[i] cur[j] then
			(
				find = true
			)
		)
		if not find then
		(
			appendIfUnique prev_only pre[i]
		)
	)
	for j = 1 to cur.count do
	(
		local find = false
		for i = 1 to pre.count do
		(
			if isSameNode pre[i] cur[j] then
			(
				find = true
				appendIfUnique the_same cur[j]
			)
		)
		if not find then
		(
			appendIfUnique last_only cur[j]
		)
	)
	print "COMPARE SCHEMATIC INFORMATION SUCCEEDED"
	return schem_diff_result prev_only last_only the_same
)

---------------------------------------------
-- UIEntity Light Config Export
---------------------------------------------
fn ExportUIEntityLightCfg filename = 
(
	local basePoint = getNodeByName "basepoint"
	if basePoint == undefined then 
	(
		messagebox "找不到基准点，请添加基准点虚拟体，并命名为 basepoint!" title:"警告！"
	)
	else
	(
		local xmlDoc = dotNetObject "system.xml.xmlDocument"
		local xmlRoot = xmlDoc.CreateElement "Lights" 
		xmlDoc.AppendChild xmlRoot
		
		local ptCount = 0
		local drCount = 0
		
		for l in lights do
		(
			if iskindof l light do
			(
				if l.type == #omni then 
				(

					local xmlLight = xmlDoc.CreateElement "PtLight" 
					xmlLight.SetAttribute "Type" "Point"
					
					local strColor = ((l.rgb.r as integer) as string) + "," + ((l.rgb.g as integer) as string)+ "," + ((l.rgb.b as integer) as string) + ",255"
					
					xmlLight.SetAttribute "color" strColor
					xmlLight.SetAttribute "mul" (l.multiplier as string)
					xmlLight.SetAttribute "radius" (l.DecayRadius as string)
					
					local reldist = l.pos - basePoint.pos
					xmlLight.SetAttribute "reldist" (reldist.x as string + "," + reldist.y as string + "," + reldist.z as string)
					
					xmlRoot.AppendChild xmlLight
					
					ptCount+=1
					
				)
				else if l.type == #freeDirect or l.type == #targetDirect then
				(
					local xmlLight = xmlDoc.CreateElement "DirLight" 
					
					local strColor = ((l.rgb.r as integer) as string) + "," + ((l.rgb.g as integer) as string) + "," + ((l.rgb.b as integer) as string) + ",255"
					
					xmlLight.SetAttribute "Type" "Dir"
					xmlLight.SetAttribute "color" strColor
					xmlLight.SetAttribute "mul" (l.multiplier as string)
					
					local dir = -l.dir;
					xmlLight.SetAttribute "dir" (dir.x as string + ","+ dir.y as string + "," + dir.z as string)
					
					xmlRoot.AppendChild xmlLight
					
					drCount+=1
				)
			)
		)
		
		if ptCount > 4 or drCount > 1 then
			messagebox "点光或者方向光的数量超出最大数量，多出灯光将不起作用！（方向光最多1盏、点光最多4盏）" title:"警告！"
			
		xmlDoc.Save(filename)
	)
)
